package com.ruoyi.face.util;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.face.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.constant.CacheConstants;

@Component
public class UserRedisCache {

    private static final Integer EXPIRE_TIME = 24; // 缓存过期时间
    private static final TimeUnit EXPIRE_TIME_UNIT = TimeUnit.HOURS;
    @Autowired
    private RedisCache redisCache;


    /**
     * 将用户人脸信息添加到 Redis 缓存
     *
     * @param userInfo 用户人脸信息
     */
    public void addUser(UserInfo userInfo) {
        String key = CacheConstants.USER_FACE_KEY_PREFIX + userInfo.getName();
        redisCache.setCacheObject(key, userInfo, EXPIRE_TIME, EXPIRE_TIME_UNIT);
    }

    /**
     * 从 Redis 缓存中移除用户
     *
     * @param name 用户name
     */
    public void removeUser(String name) {
        String key = CacheConstants.USER_FACE_KEY_PREFIX + name;
        redisCache.deleteObject(key);
    }

    /**
     * 根据name获取用户信息
     *
     * @param name 用户name
     * @return 用户信息
     */
    public UserInfo getUser(String name) {
        String key = CacheConstants.USER_FACE_KEY_PREFIX + name;
        return redisCache.getCacheObject(key);
    }

    /**
     * 获取所有用户列表
     *
     * @return 用户信息列表
     */
    public List<UserInfo> getUserList() {
        List<UserInfo> userInfoList = new ArrayList<>();
        Collection<String> keys = redisCache.keys(CacheConstants.USER_FACE_KEY_PREFIX + "*");
        Set<String> keySet = new HashSet<>(keys);
        for (String key : keySet) {
            UserInfo userInfo = redisCache.getCacheObject(key);
            if (userInfo != null) {
                userInfoList.add(userInfo);
            }
        }
        return userInfoList;
    }

    public void clear() {
        Collection<String> keys = redisCache.keys(CacheConstants.USER_FACE_KEY_PREFIX + "*");
        redisCache.deleteObject(keys);
    }

}